package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.cloud.netflix.zuul.util.RequestContentDataExtractor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 木木
 * @Email 1194660762@qq.com
 * @date 2021-08-16 9:32
 */
@Component
@Slf4j
public class AccessFilter extends ZuulFilter {
    //过滤器的类型: pre, routing, post, error
    @Override
    public String filterType() {
//        return "pre";
        return FilterConstants.PRE_TYPE;
    }

    //顺序号
    //zuul有五个默认的过滤器
    //在第5个过滤器中，向上下文对象添加了 serviceId属性
    //后面的过滤器才能访问 serviceId
    @Override
    public int filterOrder() {
        return 6;
    }

    //针对当前请求，是否要执行过滤代码
    //请求商品要检查权限，请求用户和订单不检查权限
    @Override
    public boolean shouldFilter() {
        //判断当前调用的后台服务，是不是item-service

        //获得调用的服务id
        RequestContext context = RequestContext.getCurrentContext();
        String serviceId = (String) context.get(FilterConstants.SERVICE_ID_KEY);
        //如果id是item-service，返回true
        return "item-service".equals(serviceId);
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //接收token参数
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = request.getParameter("token");
        //如果没有token，阻止继续调用,直接返回响应
        //null，“”，”  “
        if (StringUtils.isBlank(token)) {
            //阻止继续调用
            context.setSendZuulResponse(false);
            //直接返回响应
            //JsonResult - {code:xx,msg:xx,data:null}
            String json = JsonResult.err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("Not Login! 未登录！")
                    .toString();
            context.addZuulResponseHeader(
                    "Content-Type", "application/json;charset=UTF-8");
            context.setResponseBody(json);
        }
        //zuul当前版本中没有使用这个返回值，不起任何作用
        return null;
    }
}
